package emulator.GUI.io;

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import emulator.util.AddressRange;

import layout.SpringUtilities;

@SuppressWarnings("serial")
public class IrqPanel extends JPanel
{
	private JTextField flagsEdit = new JTextField("%MMMMMMMM");
	private JTextField maskEdit = new JTextField("%MMMMMMMM");
	private JTextField activeEdit = new JTextField("%MMMMMMMM");
	
	public IrqPanel()
	{
		super();
		initPanel();
	}

	private void initPanel()
	{
		setLayout(new SpringLayout());
		setBorder(BorderFactory.createTitledBorder("IRQ"));
		add(new JLabel("Flags"));
		add(flagsEdit);
		add(new JLabel("Mask"));
		add(maskEdit);
		add(new JLabel("Active"));
		add(activeEdit);
		activeEdit.setEditable(false);
		
		SpringUtilities.makeGrid(this,
                3, 2, //rows, cols
                5, 5, //initialX, initialY
                5, 5);//xPad, yPad
	}

	public void setFlagsValue(int flagsValue)
	{
		flagsEdit.setText("%"+AddressRange.toBinaryString(flagsValue, 8));
		updateActiveStatus();
	}

	public int getFlagsValue()
	{
		return AddressRange.addressFromString(flagsEdit.getText());
	}

	public void setMaskValue(int maskValue)
	{
		maskEdit.setText("%"+AddressRange.toBinaryString(maskValue, 8));
		updateActiveStatus();
	}

	public int getMaskValue()
	{
		return AddressRange.addressFromString(maskEdit.getText());
	}

	private void updateActiveStatus()
	{
		try {
			int active = getFlagsValue() & getMaskValue();
			activeEdit.setText("%"+AddressRange.toBinaryString(active, 8));
			activeEdit.setForeground(active > 0 ? Color.BLACK : Color.GRAY);
		} 
		catch (NumberFormatException ex)
		{ }
	}

}
